package com.grm.service;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.AbstractContextMapper;
import org.springframework.ldap.filter.EqualsFilter;
import org.springframework.stereotype.Service;

import javax.naming.NamingException;
import java.util.List;

import static org.springframework.ldap.query.LdapQueryBuilder.query;

@Service
public class LdapService {
    @Autowired
    private LdapTemplate ldapTemplate;


    public Boolean requestLdap(String username, String password) {
        EqualsFilter filter = new EqualsFilter("sAMAccountName", username);

        return ldapTemplate.authenticate("", filter.toString(), password);
    }

    public Boolean emailRequest(String username, String password) {
        EqualsFilter filter = new EqualsFilter("userPrincipalName", username);
        return ldapTemplate.authenticate("", filter.toString(), password);
    }

    /**
     * 查询用户是否存在
     *
     * @param username 用户名
     * @return boolean
     */
    public Boolean userIsExists(String username) {
        List<String> results = ldapTemplate.search(query().where("sAMAccountName").is(username), new AbstractContextMapper<String>() {
            @Override
            protected String doMapFromContext(DirContextOperations ctx) {
                return ctx.getNameInNamespace();
            }
        });
        if (results.size() > 0) {
            return true;
        }
        return false;
    }
}
